package com.ziyun.erp.modules.production.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.utility.New;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.capital.MerchantTypeEnum;
import com.ziyun.erp.common.e.goods.GoodsTypeEnum;
import com.ziyun.erp.common.e.order.*;
import com.ziyun.erp.common.e.production.AllotTypeEnum;
import com.ziyun.erp.common.e.production.FinanceStatusEnum;
import com.ziyun.erp.common.e.production.OrderProductionStatusEnum;
import com.ziyun.erp.common.e.production.ProducerTypeEnum;
import com.ziyun.erp.common.utils.ErpOrderUtils;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.freightages.service.SdbEctoolsRegionsService;
import com.ziyun.erp.modules.logistics.service.LogisticsTypeService;
import com.ziyun.erp.modules.order.dto.OrderCraftQuoteDto;
import com.ziyun.erp.modules.order.entity.*;
import com.ziyun.erp.modules.order.service.*;
import com.ziyun.erp.modules.order.vo.OrderCraftServerVo;
import com.ziyun.erp.modules.order.vo.UserAccessoryVo;
import com.ziyun.erp.modules.otherAccessory.entity.OtherAccessoryEntity;
import com.ziyun.erp.modules.otherAccessory.service.OtherAccessoryService;
import com.ziyun.erp.modules.production.dao.ErpOrderProductionDao;
import com.ziyun.erp.modules.production.dto.FinancePaymentDto;
import com.ziyun.erp.modules.production.dto.ProductionCostDto;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.erp.modules.production.operate.ErpOrderStateContext;
import com.ziyun.erp.modules.production.operate.ProduceFinishState;
import com.ziyun.erp.modules.production.operate.WaitReceiveState;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import com.ziyun.erp.modules.production.service.ErpOrderProductionService;
import com.ziyun.erp.modules.production.vo.ErpOrderProductionListVo;
import com.ziyun.erp.modules.supp.entity.SellerInfoEntity;
import com.ziyun.erp.modules.supp.service.SellerInfoService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("erpOrderProductionService")
public class ErpOrderProductionServiceImpl extends ServiceImpl<ErpOrderProductionDao, ErpOrderProductionEntity> implements ErpOrderProductionService {

    @Autowired
    private SdbEctoolsRegionsService sdbEctoolsRegionsService;
    @Autowired
    private LogisticsTypeService logisticsTypeService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ErpOrderItemService erpOrderItemService;
    @Autowired
    private ErpOrderService erpOrderService;
    @Autowired
    private ErpOrderProductionService erpOrderProductionService;
    @Autowired
    private SellerInfoService sellerInfoService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private UserAccessoryService userAccessoryService;
    @Autowired
    private ErpOrderLogService erpOrderLogService;
    @Autowired
    private OrderRemarksService orderRemarksService;
    @Autowired
    private OtherAccessoryService otherAccessoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String orderNo = StringUtil.getRequestParamString(params.get("orderNo"));
        String productionStatus = StringUtil.getRequestParamString(params.get("productionStatus"));

        Page<ErpOrderProductionEntity> page = this.selectPage(
                new Query<ErpOrderProductionEntity>(params).getPage(),
                new EntityWrapper<ErpOrderProductionEntity>()
                        .like(StringUtils.isNotBlank(orderNo), "order_no", orderNo)
                        .like(StringUtils.isNotBlank(productionStatus), "production_status", productionStatus)
        );

        return new PageUtils(page);
    }

    @Override
    public R queryPageProductionList(Map<String, Object> params) {
        List<Integer> types = new ArrayList<>();
        types.add(ThirdMerchantTypeEnum.ZIYUN.toInt());
        params.put("thirdMerchantType", types);

        int totalCount = this.baseMapper.countProduction(params);
        int current = Integer.valueOf((String) params.get("page"));
        int size = Integer.valueOf((String) params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<ErpOrderProductionListVo> list = this.baseMapper.queryPageProductionList(params);

        // 查询图片信息
        List<String> sendPicsList = list.stream().filter(item -> StringUtils.isNotBlank(item.getSendPics()))
                .map(ErpOrderProductionListVo::getSendPics)
                .collect(Collectors.toList());
        if (sendPicsList.size() > 0){
            Set<String> pics = New.hashSet();
            for (String str : sendPicsList){
                String[] split = str.split(",");
                Set<String> strSet = new HashSet<String>(Arrays.asList(split));
                pics.addAll(strSet);
            }
            List<OtherAccessoryEntity> accessoryList = otherAccessoryService.selectList(new EntityWrapper<>(
                    new OtherAccessoryEntity()).in("id", pics)
                    .eq("disabled", DeleteEnum.NOT_DELETE.toInt())
            );
            if (accessoryList.size() > 0){
                for (ErpOrderProductionListVo erpOrderProductionListVo : list){
                    String sendPics = erpOrderProductionListVo.getSendPics();
                    if (StringUtils.isNotBlank(sendPics)){
                        String[] split = sendPics.split(",");
                        List<String> ids = Arrays.asList(split);
                        Optional<OtherAccessoryEntity> first = accessoryList.stream().filter(item -> ids.contains(item.getId().toString())).findFirst();
                        if (first.isPresent()){
                            OtherAccessoryEntity otherAccessory = first.get();
                            String imageUrl = otherAccessory.getImageUrl();
                            erpOrderProductionListVo.setSendPicsUrl(imageUrl);
                            erpOrderProductionListVo.setSize(otherAccessory.getSize());
                        }
                    }
                }
            }
        }

        // 生产状态
        Map<String, Object> userData = new HashMap<>();
        userData.put("orderProductionStatusEnum", JsonUtils.enumToList(OrderProductionStatusEnum.class));
        userData.put("financeStatusEnum", JsonUtils.enumToList(FinanceStatusEnum.class));
        userData.put("producerTypeEnum", JsonUtils.enumToList(ProducerTypeEnum.class));
        userData.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));
        // 外协跟单员
        List<ErpCustomerServieceUserEntity> pmcIdList = erpOrderService.getCsOrPmcList(2);
        userData.put("pmcIdList", pmcIdList);
        // 查询自营门店
        List<Integer> ids = new ArrayList<>();
        ids.add(18);
        ids.add(20);
        List<SellerInfoEntity> sellerInfoList = sellerInfoService.selectList(new EntityWrapper<>(new SellerInfoEntity())
                .eq("seller_type", MerchantTypeEnum.SMALL_B.toCode())
                .eq("self", 1)
                .notIn("seller_id", ids)
        );
        userData.put("sellerInfoList", sellerInfoList);

        R r = R.ok();
        r.put("page", new PageUtils(list, totalCount, size, current));
        r.put("userData", userData);
        return r;
    }

    public R getProducerList(String producerName){
        Map<String, Object> params = New.hashMap(1);
        params.put("producerName", producerName);
        List<String> producerNames = baseMapper.selectProducerOptions(params);
        return R.ok().put("producerNames", producerNames);
    }

    @Override
    public R storelist(Map<String, Object> params) {
        List<Integer> types = new ArrayList<>();
        types.add(ThirdMerchantTypeEnum.ZIYUN_MERCHANT.toInt());
        params.put("thirdMerchantType", types);
        params.put("onlineCash", 1);
        int totalCount = this.baseMapper.countProduction(params);
        int current = Integer.valueOf((String) params.get("page"));
        int size = Integer.valueOf((String) params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<ErpOrderProductionListVo> list = this.baseMapper.queryPageProductionList(params);

        // 添加客服备注
        for (ErpOrderProductionListVo erpOrderProduction : list) {
            String orRemarks = this.baseMapper.getAllRemark(erpOrderProduction.getOrderNo());
            erpOrderProduction.setOrRemarks(orRemarks);
        }

        // 生产状态
        Map<String, Object> userData = new HashMap<>();
        userData.put("orderProductionStatusEnum", JsonUtils.enumToList(OrderProductionStatusEnum.class));
        userData.put("financeStatusEnum", JsonUtils.enumToList(FinanceStatusEnum.class));
        userData.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));

        // 查询自营门店
        List<Integer> ids = new ArrayList<>();
//        ids.add(1);
        ids.add(18);
        ids.add(20);
        List<SellerInfoEntity> sellerInfoList = sellerInfoService.selectList(new EntityWrapper<>(new SellerInfoEntity())
                .eq("seller_type", MerchantTypeEnum.SMALL_B.toCode())
                .eq("self", 1)
                .notIn("seller_id", ids)
        );
        userData.put("sellerInfoList", sellerInfoList);

        R r = R.ok();
        r.put("page", new PageUtils(list, totalCount, size, current));
        r.put("userData", userData);
        return r;
    }

    @Override
    public R sellerlist(Map<String, Object> params) {
        List<Integer> types = new ArrayList<>();
        types.add(ThirdMerchantTypeEnum.ZIYUN.toInt());
        params.put("thirdMerchantType", types);
        params.put("producer", ErpOrderStateContext.MAICAI_SELLER_ID);
        params.put("onlineCash", 1);
        int totalCount = this.baseMapper.countProduction(params);
        int current = Integer.valueOf((String) params.get("page"));
        int size = Integer.valueOf((String) params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<ErpOrderProductionListVo> list = this.baseMapper.queryPageProductionList(params);

        // 添加客服备注
        for (ErpOrderProductionListVo erpOrderProduction : list) {
            String orRemarks = this.baseMapper.getAllRemark(erpOrderProduction.getOrderNo());
            erpOrderProduction.setOrRemarks(orRemarks);
        }

        // 生产状态
        Map<String, Object> userData = new HashMap<>();
        userData.put("orderProductionStatusEnum", JsonUtils.enumToList(OrderProductionStatusEnum.class));
        userData.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));

        R r = R.ok();
        r.put("page", new PageUtils(list, totalCount, size, current));
        r.put("userData", userData);
        return r;
    }

    @Override
    public R productcostlist(Map<String, Object> params) {
        Page<ErpOrderProductionListVo> page = new Page<>(Integer.parseInt(params.get("page").toString()),
                Integer.parseInt(params.get("limit").toString()));
        page.setRecords(this.baseMapper.selectProductionList(page, params));
        PageUtils pageUtils = new PageUtils(page);
        // 合计金额
        Double totalPrice = this.baseMapper.sumProductionCost(params);
        Map<String, Object> userData = new HashMap<>();
        userData.put("totalPrice", totalPrice);
        // 查询自营门店
        List<Integer> ids = new ArrayList<>();
//        ids.add(1);
        ids.add(18);
        ids.add(20);
        List<SellerInfoEntity> sellerInfoList = sellerInfoService.selectList(new EntityWrapper<>(new SellerInfoEntity())
                .eq("seller_type", MerchantTypeEnum.SMALL_B.toCode())
                .eq("self", 1)
                .notIn("seller_id", ids)
        );
        userData.put("sellerInfoList", sellerInfoList);

        R r = R.ok();
        r.put("page", pageUtils);
        r.put("userData", userData);
        return r;
    }

    @Override
    public List<ErpOrderProductionListVo> queryProductionList(Map<String, Object> params) {
        return this.baseMapper.queryProductionList(params);
    }

    @Override
    public void erpOrderItemAddLogistics(OrderInfoEntity orderInfo, Integer logiType) {
        String orderId = orderInfo.getOrderId();
        String shipStatus = orderInfo.getShipStatus();
        if (!StringUtils.equals(shipStatus, ShipStatusEnum.shipped.toCode())) {
            Map<String, Object> updateMap = new HashMap<>();
            Date currDate = new Date();
            ErpOrderEntity erpOrder = erpOrderService.selectById(orderId);
            if (erpOrder == null) {
                erpOrder = ErpOrderUtils.ziyunOrderToErp(orderInfo);
                erpOrder.setShipStatus(Integer.valueOf(ShipStatusEnum.shipped.toCode()));
                erpOrder.setSendTime(currDate);
                if (logiType.intValue() == 3) {// 自提
                    erpOrder.setDeliveryTime(currDate);
                } else {// 非自提，默认7天确认收货
                    erpOrder.setDeliveryTime(DateUtils.addDateDays(currDate, 7));
                }
                erpOrderService.insert(erpOrder);
                List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderId));
                List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList, orderId);
                erpOrderItemService.insertBatch(erpOrderItemEntityList);
            } else {
                updateMap.put("shipStatus", ShipStatusEnum.shipped.toCode());
                updateMap.put("sendTime", DateUtils.format(currDate, "yyyy-MM-dd HH:mm:ss"));
                if (logiType.intValue() == 3) {// 自提
                    updateMap.put("deliveryTime", DateUtils.format(currDate, "yyyy-MM-dd HH:mm:ss"));
                } else {// 非自提，默认7天确认收货
                    updateMap.put("deliveryTime", DateUtils.format(DateUtils.addDateDays(currDate, 7), "yyyy-MM-dd HH:mm:ss"));
                }
                erpOrderService.updateByMap(updateMap, orderId);
            }

            updateMap.clear();
            updateMap.put("shipStatus", ShipStatusEnum.shipped.toCode());
            orderInfoService.updateByMap(updateMap, orderId);
        }
    }

    @Override
    public void erpOrderItemFinish(String orderNo) {
        // 查询订单下所有商品是否都已生产完成
        List<Integer> status = new ArrayList<>();
        status.add(OrderItemStatusEnum.PRODUCTION_FINISH.toInt());
        status.add(OrderItemStatusEnum.DELIVERED.toInt());
        int selectCount = erpOrderItemService.selectCount(new EntityWrapper<>(new ErpOrderItemEntity())
                .eq("order_no", orderNo)
                .notIn("status", status)
                .eq("item_del", DeleteEnum.NOT_DELETE.toInt())
        );
        if (selectCount == 0) {
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("productionStatus", ProductionStatusEnum.PRODUCTION_FINISH.toInt());
            updateMap.put("finishTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            erpOrderService.updateByMap(updateMap, orderNo);
        }
    }

    @Override
    public void productionFinish(Integer erpItemId) {
        // 查询商品下所有生产单是否生产完成
        List<Integer> notInStatus = new ArrayList<>();
        notInStatus.add(OrderProductionStatusEnum.FINISH.toInt());
        notInStatus.add(OrderProductionStatusEnum.CANCLE.toInt());
        int selectCount = erpOrderProductionService.selectCount(new EntityWrapper<>(new ErpOrderProductionEntity())
                .eq("erp_item_id", erpItemId)
                .eq("del", DeleteEnum.NOT_DELETE.toInt())
                .notIn("production_status", notInStatus)
        );
        if (selectCount == 0) {
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("status", OrderItemStatusEnum.PRODUCTION_FINISH.toInt());
            erpOrderItemService.updateByMap(updateMap, erpItemId);
        }
    }

    @Override
    public R queryExpressFormInfo(String orderNo) {
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderNo);
        Integer thirdMerchantId = erpOrder.getThirdMerchantId();
        SellerInfoEntity sellerInfo = sellerInfoService.selectById(thirdMerchantId);

        return R.ok().put("erpOrder", erpOrder)
                .put("sellerInfo", sellerInfo);
    }

    @Override
    public boolean updateBatchByMap(Map<String, Object> updateMap, List<Integer> proIds) {
        int update = this.baseMapper.updateBatchByMap(updateMap, proIds);
        if (update == 0) {
            return false;
        }
        return true;
    }

    @Override
    public R sendYangluoLogisticsInfo(String productionIds) {
        // 订单信息
        List<String> ids = Arrays.asList(productionIds.split(","));
        List<ErpOrderEntity> erpOrderEntityList = erpOrderService.queryListByProductionId(ids);
        if (erpOrderEntityList == null || erpOrderEntityList.size() != 1) {
            return R.error("请勾选相同订单号添加物流");
        }
        ErpOrderEntity erpOrder = erpOrderEntityList.get(0);

        // 商品列表
        List<Integer> statusList = new ArrayList<>();
        statusList.add(OrderItemStatusEnum.IN_PRODUCTION.toInt());
        statusList.add(OrderItemStatusEnum.DELIVERED.toInt());
        List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.selectList(
                new EntityWrapper<ErpOrderItemEntity>()
                        .eq("order_no", erpOrder.getOrderNo())
                        .in("status", statusList)
                        .eq("item_del", 0)
        );
        // 查询省市区级联数据
        List<String> area = sdbEctoolsRegionsService.queryRegionsSascade();
        // 物流类型
        List<Map<Integer, String>> logisticsTypeList = logisticsTypeService.queryTypeList();
        return R.ok().put("erpOrder", erpOrder)
                .put("erpOrderItemEntityList", erpOrderItemEntityList)
                .put("area", JSONArray.fromObject(area).toString())
                .put("logisticsTypeList", logisticsTypeList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderDiscount(ProductionCostDto productionCostDto, String username) {
        Integer productionId = productionCostDto.getProductionId();
        ErpOrderProductionEntity erpOrderProduction = this.selectById(productionId);
        String orderNo = erpOrderProduction.getOrderNo();
        String productionOrder = erpOrderProduction.getProductionOrder();
        OrderInfoEntity orderInfoAllot = orderInfoService.selectById(productionOrder);
        String payStatus = orderInfoAllot.getPayStatus();
        if (payStatus.equals(PayStatusEnum.ALREADY_PAY_1.toCode())) {
            return R.error("订单已审核完成");
        }

        BigDecimal nowDiscount = productionCostDto.getDiscount();
        BigDecimal oldDiscount = orderInfoAllot.getDiscount();
        BigDecimal oldPayableAmount = orderInfoAllot.getPayableAmount();
        BigDecimal nowPayableAmount = oldPayableAmount.subtract(oldDiscount).add(nowDiscount);
        int compare = nowPayableAmount.compareTo(BigDecimal.ZERO);
        if (compare <= 0) {
            return R.error("应付金额应大于0，调价失败");
        }

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("discount", nowDiscount);
        updateMap.put("payableAmount", nowPayableAmount);
        orderInfoService.updateByMap(updateMap, productionOrder);
        erpOrderService.updateByMap(updateMap, productionOrder);

        updateMap.clear();
        updateMap.put("cost", nowPayableAmount);
        erpOrderProductionService.updateByMap(updateMap, productionId);

        String remark = productionCostDto.getRemark();
        OrderRemarksEntity orderRemarksEntity = new OrderRemarksEntity();
        orderRemarksEntity.setOrOrderId(Long.valueOf(orderNo));
        orderRemarksEntity.setOrRemarks(remark);
        orderRemarksEntity.setOrCreateName(username);
        orderRemarksService.insert(orderRemarksEntity);

        erpOrderLogService.insertOrderLog(orderNo, "生产单调价，调价：" + nowDiscount + "，原调价：" + oldDiscount + "，productionId：" + productionId);

        return R.ok();
    }

    @Override
    public void updateByMap(Map<String, Object> map, Integer productionId) {
        baseMapper.updateByMap(map, productionId);
    }

    /**
     * 查询所属订单 其他生产单
     *
     * @param orderNo
     * @param productionId
     * @return
     */
    @Override
    public List<ErpOrderProductionEntity> queryOtherOrderProduction(String orderNo, Integer productionId) {
        return baseMapper.queryOtherOrderProduction(orderNo, productionId);
    }

    /**
     * 订单分配，阳逻发货
     *
     * @param eoItemId
     * @return
     */
    @Override
    public R yangluoSend(Integer eoItemId, Integer csId, Integer pmcId) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R confirmReceive(Integer productionId) {
        try {
            ErpOrderStateContext erpOrderStateContext = new ErpOrderStateContext(new WaitReceiveState(), productionId);
            R receive = erpOrderStateContext.receive();
            int code = (int) receive.get("code");
            if (code == 500) {
                return receive;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("系统异常，请联系后台管理员！");
        }
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R auditFinish(Integer productionId) {
        try {
            ErpOrderStateContext erpOrderStateContext = new ErpOrderStateContext(new ProduceFinishState(), productionId);
            R finish = erpOrderStateContext.allotPriceFinish();
            int code = (int) finish.get("code");
            if (code == 500) {
                return finish;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("系统异常，请联系后台管理员！");
        }
        return R.ok();
    }

    @Override
    public List<OrderCraftQuoteDto> selectAllotedCraftsList(Integer itemId) {
        return this.baseMapper.selectAllotedCraftsList(itemId);
    }

    @Override
    public List<OrderCraftServerVo> selectAllotedServerCraftsList(Integer erpItemId) {
        return this.baseMapper.selectAllotedServerCraftsList(erpItemId);
    }

    /**
     * 生产成本
     * 录入成本价
     */
    @Override
    public void updatecost(ErpOrderProductionEntity erpOrderProduction) {
        Integer productionId = erpOrderProduction.getProductionId();
        ErpOrderProductionEntity erpOrderProductionEntity = this.selectById(productionId);
        String orderNo = erpOrderProductionEntity.getOrderNo();

        erpOrderProduction.setCostStatus(true);
        baseMapper.updateById(erpOrderProduction);

        erpOrderLogService.insertOrderLog(orderNo, "生产成本录入，productionId：" + productionId);

    }

    /**
     * 生产成本批量录入
     * @param productionIds
     * @return
     */
    @Override
    @Transactional
    public R batchEnteringCost(Integer[] productionIds) {
        List<Integer> proIds = Arrays.asList(productionIds);
        Map<String, Object> updateMap = New.hashMap(1);
        updateMap.put("costStatus", 1);
        updateMap.put("updateName", UserUtils.getCurentUser().getUserId());
        baseMapper.updateBatchByMap(updateMap, proIds);

        List<ErpOrderProductionEntity> productionEntityList = baseMapper.selectBatchIds(proIds);
        for (ErpOrderProductionEntity erpOrderProductionEntity : productionEntityList) {
            Integer productionId = erpOrderProductionEntity.getProductionId();
            String orderNo = erpOrderProductionEntity.getOrderNo();
            erpOrderLogService.insertOrderLog(orderNo, "生产成本批量录入，productionId：" + productionId);
        }

        return R.ok();
    }

    /*生产成本/审核
     */
    @Override
    public void toExamine(Integer productionId) {
        ErpOrderProductionEntity erpOrderProductionEntity = this.selectById(productionId);
        String orderNo = erpOrderProductionEntity.getOrderNo();

        Map<String, Object> map = new HashMap<>();
        map.put("updateName", UserUtils.getCurentUser().getUserId());
        map.put("financeStatus", 2);
        baseMapper.updateByMap(map, productionId);

        erpOrderLogService.insertOrderLog(orderNo, "生产成本审核，productionId：" + productionId);

    }

    /**
     * 生产成本价 批量审核
     * @param productionIds
     * @return
     */
    @Override
    public R toBatchExamine(String productionIds) {
        if (StringUtils.isBlank(productionIds)) {
            return R.error("没有生产单信息");
        }
        String[] split = productionIds.split(",");
        List<String> list = Arrays.asList(split);
        List<ErpOrderProductionEntity> productionEntityList = this.selectBatchIds(list);

        List<Integer> ids = new ArrayList<>();
        for (String str : list) {
            ids.add(Integer.valueOf(str));
        }
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("updateName", UserUtils.getCurentUser().getUserId());
        updateMap.put("financeStatus", FinanceStatusEnum.UN_PAYD.toInt());
        baseMapper.updateBatchByMap(updateMap, ids);

        for (ErpOrderProductionEntity erpOrderProduction : productionEntityList) {
            Integer productionId = erpOrderProduction.getProductionId();
            String orderNo = erpOrderProduction.getOrderNo();
            erpOrderLogService.insertOrderLog(orderNo, "生产成本批量审核，productionId：" + productionId);
        }

        return R.ok();
    }

    /**生产成本
     * 外协金额计算
     * @param productionIds
     * @return
     */
    @Override
    public R productionCostCount(Integer[] productionIds) {
        List<ErpOrderProductionEntity> productionEntityList = this.selectBatchIds(Arrays.asList(productionIds));
        BigDecimal reduce = productionEntityList.stream().map(ErpOrderProductionEntity::getCost).reduce(BigDecimal.ZERO, BigDecimal::add);

        return R.ok().put("totalCost", reduce);
    }


    /*生产成本/订单作废
     */
    @Override
    public void toDead(ErpOrderProductionEntity erpOrderProduction) {
        Integer productionId = erpOrderProduction.getProductionId();
        ErpOrderProductionEntity erpOrderProductionEntity = this.selectById(productionId);
        String orderNo = erpOrderProductionEntity.getOrderNo();

        Map<String, Object> map = new HashMap<>();
        map.put("updateName", UserUtils.getCurentUser().getUserId());
        map.put("financeRemark", erpOrderProduction.getFinanceRemark());
        map.put("financeStatus", 11);
        baseMapper.payFromByMap(map, productionId);

        erpOrderLogService.insertOrderLog(orderNo, "生产成本作废，productionId：" + productionId);

    }


    /*生产成本/订单撤回待审
     */
    @Override
    public void toWithdraw(Integer productionId) {
        ErpOrderProductionEntity erpOrderProductionEntity = this.selectById(productionId);
        String orderNo = erpOrderProductionEntity.getOrderNo();

        Map<String, Object> map = new HashMap<>();
        map.put("updateName", UserUtils.getCurentUser().getUserId());
        map.put("financeStatus", 1);
        baseMapper.updateByMap(map, productionId);

        erpOrderLogService.insertOrderLog(orderNo, "生产成本撤回待审，productionId：" + productionId);
    }


    /*生产成本/订财务付款
     */
    @Override
    public R toPayment(FinancePaymentDto financePaymentDto) {
        String productionId = financePaymentDto.getProductionId();
        if (StringUtils.isBlank(productionId)) {
            return R.error("没有生产单号信息");
        }
        String[] split = productionId.split(",");
        List<ErpOrderProductionEntity> productionEntityList = this.selectBatchIds(Arrays.asList(split));
        long count = productionEntityList.stream().filter(item -> item.getFinanceStatus().intValue() != FinanceStatusEnum.UN_PAYD.toInt()).count();
        if (count > 0) {
            return R.error("请检查勾选 生产单付款状态 是否为待付款");
        }
        count = productionEntityList.stream().filter(item -> item.getOnlineCash().intValue() == 1 && item.getProducerType().intValue() != 2).count();
        if (count > 0) {
            return R.error("存在线上提现订单");
        }

        List<Integer> ids = new ArrayList<>();
        for (String str : split) {
            ids.add(Integer.valueOf(str));
        }
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("updateName", financePaymentDto.getUserId());
        updateMap.put("financePaytime", financePaymentDto.getFinancePaytime());
        updateMap.put("financeRemark", financePaymentDto.getFinanceRemark());
        updateMap.put("financeStatus", FinanceStatusEnum.PAYD.toInt());
        this.baseMapper.updateBatchByMap(updateMap, ids);

        for (ErpOrderProductionEntity erpOrderProduction : productionEntityList) {
            Integer pId = erpOrderProduction.getProductionId();
            String orderNo = erpOrderProduction.getOrderNo();
            erpOrderLogService.insertOrderLog(orderNo, "生产成本付款，productionId：" + pId);
        }

        return R.ok();
    }

    @Override
    public List<ErpOrderProductionListVo> exportExcel(Map<String, Object> params) {
        return this.baseMapper.exportExcel(params);
    }

    @Override
    public boolean updateByMapOrderId(Map<String, Object> updateMap, String orderId) {
        int count = this.baseMapper.updateByMapOrderId(updateMap, orderId);
        if (count == 0) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R supplierConfirmReceive(Integer productionId) {
        ErpOrderProductionEntity erpOrderProduction = this.selectById(productionId);
        String orderNo = erpOrderProduction.getOrderNo();
        Integer productionStatus = erpOrderProduction.getProductionStatus();
        String erpItemId = erpOrderProduction.getErpItemId();
        if (productionStatus.intValue() != OrderProductionStatusEnum.PRODUCING.toInt()) {
            return R.error("生产单状态异常！");
        }

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("productionStatus", OrderProductionStatusEnum.FINISH.toInt());
        this.updateByMap(updateMap, productionId);

        // 判断是否服务工序，即生产单分配类型为procedure，若是，判断商品下所有工序分配是否都已生产完成，将商品状态置为生产完成
        String allotType = erpOrderProduction.getAllotType();
        if (allotType.equals(AllotTypeEnum.PROCEDURE.toCode())) {
            // 商品状态 生产中 =》 生产完成
            this.productionFinish(Integer.valueOf(erpItemId));
            // 订单状态 生产中 =》 生产完成
            this.erpOrderItemFinish(orderNo);
        } else {
            updateMap.clear();
            updateMap.put("status", OrderItemStatusEnum.PRODUCTION_FINISH.toInt());
            erpOrderItemService.updateByMap(updateMap, Integer.valueOf(erpItemId));
        }

        erpOrderLogService.insertOrderLog(orderNo, "外协生产单验货确定：productionId：" + productionId);

        return R.ok();
    }

    @Override
    public List<ErpOrderProductionEntity> getErpOrderProductionEntity(String orderNo) {
        return this.baseMapper.getErpOrderProductionEntity(orderNo);
    }

    /**
     * 生产成本
     * 生产单复审
     * @param productionId
     * @return
     */
    @Override
    public R review(Integer productionId) {
        ErpOrderProductionEntity erpOrderProduction = this.selectById(productionId);
        String orderNo = erpOrderProduction.getOrderNo();
        Integer onlineCash = erpOrderProduction.getOnlineCash();
        Integer producerType = erpOrderProduction.getProducerType();
        // 线下外协或线上分配自营门店生产单
        if (onlineCash.intValue() == 1 && producerType.intValue() != 2) {
            return R.error("生产单不满足复审操作");
        }

        this.baseMapper.paymentProductionReview(productionId);

        erpOrderLogService.insertOrderLog(orderNo, "生产单复审：productionId：" + productionId);

        return R.ok();
    }

    @Override
    public R orderSourceFile(Integer productionId) {
        ErpOrderProductionEntity erpOrderProduction = this.selectById(productionId);
        String allotType = erpOrderProduction.getAllotType();
        List<UserAccessoryVo> userAccessoryList = null;
        if (StringUtils.endsWith(allotType, AllotTypeEnum.ORDER.toCode())) {
            String orderNo = erpOrderProduction.getOrderNo();
            userAccessoryList = userAccessoryService.queryListByOrderNo(orderNo);
        } else {
            String orderItemId = erpOrderProduction.getOrderItemId();
            userAccessoryList = userAccessoryService.queryListByItemId(orderItemId);
        }

        return R.ok().put("userAccessoryList", userAccessoryList);
    }

}
